#include "savefilethread.h"

#define _IS_PROTOCOL_ 0 // 1:带协议存储    0:直接存储

SaveFileThread::SaveFileThread(QObject *parent) : QObject(parent)
{
    m_saveMaxNum = 100;
    m_deleteWayIndex = 0;

    m_splitWayValueBytes = 100 * 1024 * 1024;   //100M = 100 * 1024 * 1024Byte

    m_currFileSize = m_splitWayValueBytes + 1;

    m_fileSavePath = nullptr;
}

void SaveFileThread::setInfo(QString targetIP, QString desc,  quint16 port, QString fileSavePath)
{
    m_targetIP = targetIP;
    m_desc = desc;
    m_port = port;

    QDir dir(QString("%1/%2").arg(fileSavePath).arg(desc));

    // 检查文件夹是否已存在
    if (dir.exists()) {
        qDebug() << "文件夹已存在: " << dir.path();

        // 检查文件数量是否超过上限
        int fileCount = getFileCount();
        if (fileCount > m_saveMaxNum) {
            deleteFiles(fileCount - m_saveMaxNum);
        }
        return;
    }

    // 尝试创建文件夹（递归创建所有父目录）
    if (dir.mkpath(".")) {
        qDebug() << "成功创建文件夹: " << dir.path();
        return ;
    } else {
        qDebug() << "创建文件夹失败: " << dir.path();
        return ;
    }
}

void SaveFileThread::setParam(const SettingsData& settingsData)
{
    m_saveMaxNum = settingsData.saveMaxNum;
    m_deleteWayIndex = settingsData.deleteWayIndex;

    m_splitWayValueBytes = settingsData.mSize * 1024 * 1024;

    m_currFileSize = m_splitWayValueBytes + 1;

    m_fileSavePath = settingsData.fileSavePath;
}

void SaveFileThread::working(const QString ip, const quint16 port, const QByteArray arr)
{
    //qDebug() << "ip:" << ip;
    //if(ip != m_targetIP || port != m_port) return;
    if(port != m_port) return;

    // 创建新文件后检查文件数量
    int fileCount = getFileCount();
    if (fileCount > m_saveMaxNum) {
        // 计算需要删除的文件数量
        int numToDelete = fileCount - m_saveMaxNum;
        deleteFiles(numToDelete);
    }

    if(m_currFileSize > m_splitWayValueBytes)  // 文件大小控制在 m_maxFileSize
    {
        m_file.close();

        QString fileName = QString("/%1/%2/%3_%4.h264").arg(m_fileSavePath).arg(m_desc)
                .arg(m_desc).arg(QDateTime::currentDateTime().toString("yyyy_MM_dd_hh_mm_ss"));

        m_file.setFileName(fileName);
        m_file.open(QIODevice::WriteOnly);
        m_currFileSize = 0;

        qDebug() << "create file : " << fileName;

        if(m_file.write(arr) == -1)
        {
            qDebug() << "写入文件失败:" << m_file.errorString();
            m_file.close();
            return;
        }

        m_currFileSize += arr.size();
    } else {

        if(m_file.write(arr) == -1)
        {
            qDebug() << "写入文件失败:" << m_file.errorString();
            m_file.close();
            return;
        }
        m_currFileSize += arr.size();
    }
}

int SaveFileThread::getFileCount()
{
    QDir dir(QString("%1/%2").arg(m_fileSavePath).arg(m_desc));

    // 检查文件夹是否存在
    if (!dir.exists()) {
        return 0;
    }

    // 获取所有文件（不包括目录）
    QFileInfoList fileList = dir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot);

    return fileList.count();
}

void SaveFileThread::deleteFiles(int numToDelete)
{
    if (numToDelete <= 0) return;

    QDir dir(QString("%1/%2").arg(m_fileSavePath).arg(m_desc));

    // 检查文件夹是否存在
    if (!dir.exists()) {
       return;
    }

    // 获取所有文件（不包括目录）
    QFileInfoList fileList = dir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot);

    // 根据标志位选择排序方式
    if (m_deleteWayIndex == 0) {
        // 按修改时间排序（最新的在前）
        std::sort(fileList.begin(), fileList.end(), [](const QFileInfo &a, const QFileInfo &b) {
            return a.lastModified() > b.lastModified();
        });

    } else {
        // 按修改时间排序（最早的在前）
        std::sort(fileList.begin(), fileList.end(), [](const QFileInfo &a, const QFileInfo &b) {
            return a.lastModified() < b.lastModified();
        });
    }

    // 删除文件
    for (int i = 0; i < qMin(numToDelete, fileList.size()); i++) {
        QFile::remove(fileList[i].absoluteFilePath());
        qDebug() << (m_deleteWayIndex ? "Deleted newest file:" : "Deleted oldest file:")
                 << fileList[i].fileName();
    }
}
